<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品图片管理 - 娃衣商城</title>
    <style>
        .product-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            padding: 20px;
        }

        .product-card {
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 8px;
        }

        .product-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            margin-bottom: 10px;
        }

        .upload-form {
            margin-top: 10px;
        }

        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }

        .success {
            background-color: #d4edda;
            color: #155724;
        }

        .error {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
<div class="product-grid">
    <c:forEach items="${goodsList}" var="goods">
        <div class="product-card">
            <img src="data:image/${goods.imageType};base64,${goods.imageData != null ? goods.imageData : ''}"
                 onerror="this.src='${pageContext.request.contextPath}/image/noproduct.png'"
                 alt="${goods.name}"
                 class="product-image">
            <h3>${goods.name}</h3>
            <p>价格: ¥${goods.price}</p>
            <form class="upload-form"
                  action="${pageContext.request.contextPath}/productImageServlet"
                  method="post"
                  enctype="multipart/form-data">
                <input type="hidden" name="productId" value="${goods.id}">
                <input type="file" name="image" accept="image/*" required>
                <button type="submit">上传图片</button>
            </form>
        </div>
    </c:forEach>
</div>

<script>
    // 处理表单提交
    document.querySelectorAll('.upload-form').forEach(form => {
        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            const formData = new FormData(e.target);
            try {
                const response = await fetch(e.target.action, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.success) {
                    // 刷新页面显示新图片
                    location.reload();
                } else {
                    alert(result.message || '上传失败');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('上传失败');
            }
        });
    });
</script>
</body>
</html>
